<?php

namespace App\Http\Controllers\Family;

use App\Models\Assessment;
use App\Models\Category;
use App\Models\Child;
use App\Models\Game;
use App\Models\Grade;
use App\Models\Tool;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;

class AssessmentController extends BaseController
{

    public function index($child_id)
    {
        $child = Child::find($child_id);

        if (empty($child)) {
            return back()->with('error', __('The page you requested was not found'))->withInput();
        }

        if (!$this->allow("family", $child)) {
            return back()->with('error', __('Sorry, you are forbidden from accessing this page.'))->withInput();
        }

        $list = Assessment::where('child_id', $child_id)->get();

        $stage = Assessment::getStage();

        return familyView('assessment.index', compact('list', 'child', 'stage'));
    }

    public function analysis($child_id)
    {
        return familyView('assessment.analysis', compact('child_id'));
    }

    public function ajaxdata($child_id){
        $child = Child::find($child_id);
        if (empty($child)){
            return response()->json(['status'=>404, 'data'=>[]]);
        }
        $list = Assessment::with("tool")->where('child_id', $child_id)->get();
        if (count($list) == 0){
            return response()->json(['status'=>400, 'data'=>[]]);
        }

        $result = [];
        foreach ($result as $item){
            if (!isset($result[$item['tool_id']])){
                $result[$item['tool_id']]['name'] = $item->tool->name;
            }

            $result[$item['tool_id']]['data'][] = ['x'=>$item->assess_time, 'y'=>$item->agedevelop];
        }
        $list->each(function($item) use (&$result){
            if (!isset($result[$item['tool_id']])){
                $result[$item['tool_id']]['name'] = $item->tool->name;
                $result[$item['tool_id']]['age']['label'] = '生理年龄';
                $result[$item['tool_id']]['agedevelop']['label'] = '发展年龄';
            }

            $result[$item['tool_id']]['age']['data'][] = ['x'=>date('m/d/Y H:i',strtotime($item->assess_time)), 'y'=>floatval($item->age)];
            $result[$item['tool_id']]['agedevelop']['data'][] = ['x'=>date('m/d/Y H:i',strtotime($item->assess_time)), 'y'=>floatval($item->agedevelop)];
        });

        return response()->json(['status'=>200, 'data'=>$result]);
    }
}
